<?php

# Includo file di configurazione generale
require_once("inc/config.inc.php");

# Includo file di funzioni comuni
require_once("inc/common.inc.php");

# Inizializzo PostgreSQL
postgresql_connect();

# Includo Sessioni PostgreSQL
require_once("inc/postgresql_session.class.php");

# Includo Dijkstra
require_once("inc/dijkstra.php");

/* --- FUNZIONE PATH SELECTION --- */
    $id_progetto = $_GET['pid'];
    
	if(empty($id_progetto)) die("Missing pid!");

    /* --- OPERAZIONI PRELIMINARI --- */
    //Calcolo offset
    $result_max = pg_query($DB['link'], "SELECT max(id_door) AS max FROM LINKS WHERE progetto = ".$id_progetto);
    $row_max = pg_fetch_assoc($result_max);
    $result_min = pg_query($DB['link'], "SELECT min(id_opera) AS min FROM OPERE WHERE progetto = ".$id_progetto);
    $row_min = pg_fetch_assoc($result_min);
    $offset = $row_max['max'] - $row_min['min'] + 1;

    /* --- CALCOLO GRAFO DEI PERCORSI --- */
    //QUERY: Seleziona aree del progetto
    $result_area = pg_query($DB['link'], "SELECT id_room FROM STANZE WHERE progetto = ".$id_progetto." ORDER BY id_room");
    while ($row_area = pg_fetch_assoc($result_area)) {
        //Reset $neighbors
        $neighbors = array();
        //QUERY: Seleziona nodi_porte comunicanti con l'area corrente
        $result_links = pg_query($DB['link'], "SELECT id_door, coordinate FROM LINKS WHERE room1 = ".$row_area['id_room']." OR room2 = ".$row_area['id_room']);
        while ($row_links = pg_fetch_assoc($result_links)) {
            $neighbors[] = array($row_links['id_door'],$row_links['coordinate']);
        }

        //QUERY: Seleziona nodi_opere appartenenti all'area corrente
        $result_opere = pg_query($DB['link'], "SELECT id_opera + ".$offset." AS new_id_opera, coordinate FROM OPERE WHERE stanza = ".$row_area['id_room']);
        while ($row_opere = pg_fetch_assoc($result_opere)) {
            $neighbors[] = array($row_opere['new_id_opera'],$row_opere['coordinate']);
        }

        //Calcolo dei links
        for($i=0; $i<count($neighbors); $i++) {
            for($j=$i; $j<count($neighbors); $j++) {
                //QUERY: Calcola distanza tra nodi vicini
                $result_distance = pg_query($DB['link'], "SELECT ST_Distance('".$neighbors[$i][1]."','".$neighbors[$j][1]."') as distance");
                $row_distance = pg_fetch_assoc($result_distance);
                $points[] = array($neighbors[$i][0], $neighbors[$j][0], $row_distance['distance']);
            }
        }
    }

    //Elaborazione grafo
    foreach ($points as $point) {
            $x = $point[0];
            $y = $point[1];
            $c = $point[2];
            $ourMap[$x][$y] = $c;
            $ourMap[$y][$x] = $c;
    }
    $fp = fopen("inc/postgis_graph_".$id_progetto.".data", "w");
    fputs($fp, $row_max['max']."\n".$offset."\n".serialize($ourMap));
    fclose($fp);
    die("Success!");